class HealthApp {
    constructor() {
        this.initAuth();
        this.initDataLoaders();
        this.setupEventListeners();
    }

    initAuth() {
        const authToken = localStorage.getItem('authToken');
        if (!authToken && !window.location.pathname.includes('login')) {
            window.location.href = '/login';
        }
    }

    initDataLoaders() {
        if (document.getElementById('elders-table')) {
            this.loadEldersData();
        }

        if (document.querySelector('.chart-container')) {
            new ChartLoader().init();
        }
    }

    async loadEldersData() {
        try {
            const response = await fetch('/api/elders');
            const data = await response.json();
            this.renderTable(data);
        } catch (error) {
            console.error('数据加载失败:', error);
        }
    }

    renderTable(data) {
        const tableBody = document.querySelector('#elders-table tbody');
        tableBody.innerHTML = data.map(item => `
      <tr>
        <td>${this.escapeHTML(item.name)}</td>
        <td>${item.age}</td>
        <td>${item.gender}</td>
        <td>${item.contact}</td>
        <td>
          <button class="btn btn-sm btn-primary edit-btn">编辑</button>
          <button class="btn btn-sm btn-danger delete-btn">删除</button>
        </td>
      </tr>
    `).join('');
    }

    setupEventListeners() {
        // 表格操作事件
        document.addEventListener('click', e => {
            if (e.target.classList.contains('delete-btn')) {
                this.handleDelete(e.target.closest('tr').dataset.id);
            }
        });

        // 表单提交
        document.getElementById('health-form')?.addEventListener('submit', e => {
            e.preventDefault();
            this.submitHealthData(new FormData(e.target));
        });
    }

    escapeHTML(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }
}

// 初始化应用
window.addEventListener('DOMContentLoaded', () => new HealthApp());